#include "music.h"
#include "ui_music.h"
#include "widget.h"

music::music(QWidget *parent)
    : HandleObj(parent)
    , ui(new Ui::music)
{
    ui->setupUi(this);

    handleUserButtonStyle(ui->PlaySongButton, "PauseSongButton.png", "QPushButton { background-color:red; border-radius:20px; }", this);
    handleButtonStyle(ui->LastSongButton, "LastSongButton.png", this);
    handleButtonStyle(ui->NextSongButton, "NextSongButton.png", this);
    handleButtonStyle(ui->FileSongButton, "FileSongButton.png", this);
    handleButtonStyle(ui->WiFiSongButton, "WiFiSongButton.png", this);
    handleButtonStyle(ui->ClothButton, "ClothButton.png", this);
    handleButtonStyle(ui->ModeSongButton, "LoopSongMode.png", this);
    handleSwitchStyle(ui->VoiceSongButton, "VoiceOpenButton.png", this);
    handleButtonStyle(ui->ToolMinButton, "ToolMinButton.png", this);
    handleButtonStyle(ui->ToolMaxButton, "ToolMaxButton.png", this);
    handleButtonStyle(ui->ToolCloseButton, "ToolCloseButton.png", this);
    handleButtonStyle(ui->SearchSongButton, "SearchSongButton.png", this);
    handleButtonStyle(ui->LogoSongButton, "MusicLogo.png", this);
    ui->VoiceSongLabel->setText("··");
    ui->SongNameLineEdit->setReadOnly(true);
    ui->SongMessageLineEdit->setReadOnly(true);
    ui->SongKindsLineEdit->setReadOnly(true);

    // 将本地音乐默认目录显示在List中
    QDir dir(localmusicPath);
    auto musicList = dir.entryList(QStringList()<<"*.mp3"<<"*.wav"<<"*flac");
    ui->SongListWidget->clear();
    for (auto file : musicList)
    {
        songlistNum++;
        localmusicList.append(QUrl::fromLocalFile(QString(localmusicPath) + file)); // 保存音乐完整路径
        QString fileNameWithoutExtension = QFileInfo(file).baseName(); // 获取不带后缀的文件名
        QListWidgetItem *item = new QListWidgetItem(QString("  %1   ").arg(songlistNum, 2, 10, QChar('0')) + fileNameWithoutExtension);
        ui->SongListWidget->addItem(item);
    }
    ui->SongKindsLineEdit->setText("(本地#"+QString::number(songlistNum)+")");
    ui->SongListWidget->setCurrentRow(0);

    // 上一首 下一首 双击的同时触发播放
    connect(ui->LastSongButton, &QPushButton::clicked, this, &music::on_PlaySongButton_clicked);
    connect(ui->NextSongButton, &QPushButton::clicked, this, &music::on_PlaySongButton_clicked);
    connect(ui->SongListWidget, &QListWidget::doubleClicked, this, &music::on_PlaySongButton_clicked);

    // 自定义工具栏
    connect(ui->ToolMinButton, &QPushButton::clicked, this, [=](){
        this->showMinimized();
    });
    connect(ui->ToolMaxButton, &QPushButton::clicked, this, [=](){
        // this->showMaximized();
        this->showNormal();
    });
    connect(ui->ToolCloseButton, &QPushButton::clicked, this, [=](){
        this->close();
        // delete this;
        // Widget *mainWidget = new Widget();
        // mainWidget->show();
    });

    audioOutput = new QAudioOutput(this); // output对象
    mediaPlayer = new QMediaPlayer(this); // 媒体播放对象
    mediaPlayer->setAudioOutput(audioOutput);
    audioOutput->setVolume(0.5);

    // 获取总播放时长、名称、专辑、歌手、歌词
    connect(mediaPlayer, &QMediaPlayer::durationChanged, this, [=](qint64 duration){
        ui->SongTimeLabel->setText(QString("%1:%2").arg(duration/1000/60, 2, 10, QChar('0')).arg(duration/1000%60, 2, 10, QChar('0')));
        ui->SongProcessSlider->setRange(0, duration);

        QString title;
        QString album;
        QString artist;

        if(songlistMode == localMode)
        {
            QMediaMetaData metaData =  mediaPlayer->metaData();
            title = metaData.value(QMediaMetaData::Title).toString();
            album = truncateString(metaData.value(QMediaMetaData::AlbumTitle).toString(), 20);
            artist = metaData.value(QMediaMetaData::ContributingArtist).toString();

        }
        else if(songlistMode == navidromeMode)
        {
            title = navidrome.titles[ui->SongListWidget->currentRow()];
            album = navidrome.albums[ui->SongListWidget->currentRow()];
            artist = navidrome.artists[ui->SongListWidget->currentRow()];
        }

        if(title.isEmpty() || isValidString(title))title = "未知歌曲";
        if(album.isEmpty() || isValidString(album))album = "未知专辑";
        if(artist.isEmpty() || isValidString(artist))artist = "未知歌手";
        ui->SongNameLineEdit->setText(title);
        ui->SongMessageLineEdit->setText("专辑："+album+"    歌手："+artist);

        // 歌词
        QString lrcFilePath;
        if(songlistMode == localMode)
            lrcFilePath =  QString(localmusicPath)+title+"-"+artist+".lrc";
        else if(songlistMode == navidromeMode)
            lrcFilePath =  QString(localmusicPath)+"navidrome/navidrome.lrc";
        QFile lrcFile(lrcFilePath);
        ui->SongWordsListWidget->clear();songtimesList.clear();

        if (lrcFile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            while (!lrcFile.atEnd())
            {
                QByteArray line = lrcFile.readLine();
                songWords = QString::fromUtf8(line).trimmed();
                QRegularExpression regex(R"(\[(\d{1,2}):(\d{2})\.(\d+)\])");
                QRegularExpressionMatch match = regex.match(songWords);
                if (!songWords.isEmpty())
                {
                    qint64 totalMilliseconds = (match.captured(1).toInt() * 60 +
                                                match.captured(2).toInt()) * 1000 +
                                                match.captured(3).toInt();  // 将时间转换为毫秒

                    songtimesList.append(totalMilliseconds);

                    songWords.remove(regex);  // 移除时间戳
                    songWords = truncateString(songWords, 18);
                    ui->SongWordsListWidget->addItem(songWords.trimmed());
                }
            }
            lrcFile.close();
            songtimesNum = 0;
            ui->SongWordsListWidget->setCurrentRow(songtimesNum);
            for(int i = 0; i < 8; ++i)
            {
                ui->SongWordsListWidget->addItem("");
                songtimesList.append(duration + 1);
            }
        }
        else
            ui->SongWordsListWidget->addItem("无法加载歌词文件");
    });
    // 获取当前播放时长
    connect(mediaPlayer, &QMediaPlayer::positionChanged, this, [=](qint64 pos){
        ui->SongPlayTimeLabel->setText(QString("%1:%2").arg(pos/1000/60, 2, 10, QChar('0')).arg(pos/1000%60, 2, 10, QChar('0')));
        ui->SongProcessSlider->setValue(pos);
        songwordsscrollBar = ui->SongWordsListWidget->verticalScrollBar();

        // 遍历歌词时间列表，找到当前播放时间对应的歌词索引
        if(pos >= songtimesList.value(songtimesNum+1))
        {
            for (int i = 0; i < songtimesList.size(); ++i)
            {
                if (pos >= songtimesList.value(i))
                {
                    songtimesNum = i;
                    if(songtimesNum > songtimesList.size() - 1)songtimesNum = songtimesList.size() - 1;
                    ui->SongWordsListWidget->setCurrentRow(songtimesNum);
                    if(songtimesNum > 2)songwordsscrollBar->setValue(std::max(0, songtimesNum - 2));
                }
            }
        }
        else if(pos <= songtimesList.value(songtimesNum?(songtimesNum-1):0))
        {
            for (int i = songtimesList.size() - 1; i >= 0 ; --i)
            {
                if (pos <= songtimesList.value(i))
                {
                    songtimesNum = i;
                    if(songtimesNum > songtimesList.size() - 1)songtimesNum = songtimesList.size() - 1;
                    ui->SongWordsListWidget->setCurrentRow(songtimesNum);
                    if(songtimesNum > 2)songwordsscrollBar->setValue(std::max(0, songtimesNum - 2));
                }
            }
        }
    });
    // 拖动滑块改变音乐进度
    connect(ui->SongProcessSlider, &QSlider::sliderMoved, mediaPlayer, &QMediaPlayer::setPosition);
    // 单击歌词跳转音乐进度
    connect(ui->SongWordsListWidget, &QListWidget::clicked, mediaPlayer, [=](){
            songtimesNum = ui->SongWordsListWidget->currentRow();
            mediaPlayer->setPosition(songtimesList.value(songtimesNum));
            ui->SongProcessSlider->setValue(songtimesList.value(songtimesNum));
            if(songtimesNum > 2)songwordsscrollBar->setValue(std::max(0, songtimesNum - 2));
    });
    // 音乐结束切换模式
    connect(mediaPlayer, &QMediaPlayer::mediaStatusChanged, this, [=](QMediaPlayer::MediaStatus states){
        if(states == QMediaPlayer::MediaStatus::EndOfMedia)
            emit ui->NextSongButton->clicked();
    });
}

music::~music()
{
    delete ui;
}

// 登陆Navidrome
void music::loginNavidrome()
{
    QNetworkAccessManager *manager_token = new QNetworkAccessManager(this);

    QUrl url_token("http://118.31.36.199:4533/auth/login"); // 替换为你的 Navidrome 登录地址
    QNetworkRequest request_token(url_token);
    request_token.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject json;
    json["username"] = "LeeStone";
    json["password"] = "20040722LxL";

    QJsonDocument jsonDoc(json);
    QByteArray jsonData = jsonDoc.toJson();
    QNetworkReply *reply_token = manager_token->post(request_token, jsonData);

    // 创建事件循环
    QEventLoop eventLoop;

    // 连接finished信号到事件循环的quit槽
    connect(reply_token, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    // 开始事件循环并等待HTTP请求完成
    eventLoop.exec();

    if (reply_token->error() == QNetworkReply::NoError)
    {
        QByteArray response = reply_token->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
        QJsonObject jsonObj = jsonDoc.object();
        navidromeToken = jsonObj["token"].toString(); // 获取 Bearer Token
        navidromeID = jsonObj["id"].toString();
    }
    else
        qInfo() << "Login Error:" << reply_token->errorString();

    reply_token->deleteLater();
}

// 获取Navidrome歌曲列表（随机99首）
void music::getNavidromeSongList()
{
    loginNavidrome();

    QUrl url("http://118.31.36.199:4533/api/song?_start=0&_end=99&_sort=random");

    QNetworkRequest request(url);
    request.setRawHeader("x-nd-authorization", ("Bearer " + navidromeToken).toUtf8());
    request.setRawHeader("x-nd-client-unique-id", navidromeID.toUtf8());

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkReply *reply = manager->get(request);

    // 创建事件循环
    QEventLoop eventLoop;

    // 连接finished信号到事件循环的quit槽
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    // 开始事件循环并等待HTTP请求完成
    eventLoop.exec();

    if (reply->error() == QNetworkReply::NoError)
    {
        QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll());
        QJsonArray playlists = jsonDoc.array();

        navidrome.titles.clear();
        navidrome.albums.clear();
        navidrome.artists.clear();
        navidrome.ids.clear();

        for (const QJsonValue &value : playlists)
        {
            if (value.isObject())
            {
                QJsonObject obj = value.toObject();

                // 提取曲名、专辑和歌手
                if (obj.contains("title"))
                    navidrome.titles.append(obj["title"].toString());
                if (obj.contains("album"))
                    navidrome.albums.append(obj["album"].toString());
                if (obj.contains("artist"))
                    navidrome.artists.append(obj["artist"].toString());
                if (obj.contains("id"))
                    navidrome.ids.append(obj["id"].toString());
            }
        }
    }
    else
        qDebug() << "Error:" << reply->errorString();

    reply->deleteLater();
}

// 播放Navidrome单曲
void music::playNavidromeSong(int index)
{
    ui->SongNameLineEdit->setText(navidrome.titles[index]);
    ui->SongMessageLineEdit->setText("专辑："+navidrome.albums[index]+"    歌手："+navidrome.artists[index]);
    ui->SongWordsListWidget->clear();
    ui->SongWordsListWidget->addItem("加载中，请稍等...");
    mediaPlayer->stop();

    QString token = generateToken("20040722LxL", "c19b2d");
    QString id = navidrome.ids[index];

    QString url = QString("http://118.31.36.199:4533/rest/stream?id="+id+"&maxBitRate=128&format=mp3&u=LeeStone&t="+token+"&s=c19b2d&v=1.16.1&c=navidrome");
    QNetworkRequest request(url);

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkReply *reply = manager->get(request);

    // 创建事件循环
    QEventLoop eventLoop;

    // 连接finished信号到事件循环的quit槽
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    // 开始事件循环并等待HTTP请求完成
    eventLoop.exec();

    QString filePath = QString(QString(localmusicPath) + "navidrome/navidrome" + QString::number(index) + ".mp3");
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray data = reply->readAll();
        QFile file(filePath);

        // 打开文件以写入
        if (file.open(QIODevice::WriteOnly))
        {
            // 将数据写入文件
            file.write(data);
            file.close();
        }
        else
            qDebug() << "Failed to open file for writing:" << filePath;
    }
    else
    {
        qDebug() << "Error:" << reply->errorString();
        ui->SongWordsListWidget->clear();
        ui->SongWordsListWidget->addItem("加载失败，请检查网络...");
    }

    reply->deleteLater();

    getNavidromeSongWords(index);

    // 设置媒体源并播放
    mediaPlayer->setSource(QUrl::fromLocalFile(filePath));
    mediaPlayer->play();
}

// 获取当前播放歌曲的歌词
void music::getNavidromeSongWords(int index)
{
    QString url = QString("http://api.lrc.cx/api/v1/lyrics/single?&title="+navidrome.titles[index]+"&album="+navidrome.albums[index]+"&artist="+navidrome.artists[index]);
    QNetworkRequest request(url); //118.31.36.199:28883

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkReply *reply = manager->get(request);

    // 创建事件循环
    QEventLoop eventLoop;

    // 连接finished信号到事件循环的quit槽
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    // 开始事件循环并等待HTTP请求完成
    eventLoop.exec();

    QString filePath = QString(QString(localmusicPath) + "navidrome/navidrome.lrc");
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray data = reply->readAll();
        QFile file(filePath);

        // 打开文件以写入
        if (file.open(QIODevice::WriteOnly))
        {
            // 将数据写入文件
            file.write(data);
            file.close();

            // 设置媒体源并播放
            mediaPlayer->setSource(QUrl::fromLocalFile(filePath));
            mediaPlayer->play();
        }
        else
            qDebug() << "Failed to open file for writing:" << filePath;

    }
    else
    {
        qDebug() << "Error:" << reply->errorString();
        ui->SongWordsListWidget->clear();
        ui->SongWordsListWidget->addItem("加载失败，请检查网络...");
    }

    reply->deleteLater();
}

// 搜索栏
void music::searchNavidromeSongList(QString query)
{
    QString token = generateToken("20040722LxL", "c19b2d");

    QString url = QString("http://118.31.36.199:4533/rest/search2?query="+query+"&u=LeeStone&t="+token+"&s=c19b2d&v=1.16.1&c=navidrome");
    QNetworkRequest request(url);

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkReply *reply = manager->get(request);

    // 创建事件循环
    QEventLoop eventLoop;

    // 连接finished信号到事件循环的quit槽
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);

    // 开始事件循环并等待HTTP请求完成
    eventLoop.exec();

    if (reply->error() == QNetworkReply::NoError)
    {
        QString data = reply->readAll();
        QXmlStreamReader xml(data);

        navidrome.titles.clear();
        navidrome.albums.clear();
        navidrome.artists.clear();
        navidrome.ids.clear();

        while (!xml.atEnd() && !xml.hasError())
        {
            xml.readNext();
            if (xml.isStartElement())
            {
                if (xml.name() == QString("song"))
                {
                    QXmlStreamAttributes attributes = xml.attributes();
                    navidrome.titles.append(attributes.value("title").toString());
                    navidrome.albums.append(attributes.value("album").toString());
                    navidrome.artists.append(attributes.value("artist").toString());
                    navidrome.ids.append(attributes.value("id").toString());
                }
            }
        }

        if (xml.hasError())
            qDebug() << "XML parsing error:" << xml.errorString();
    }
    else
    {
        qDebug() << "Error:" << reply->errorString();
        ui->SongWordsListWidget->clear();
        ui->SongWordsListWidget->addItem("加载失败，请检查网络...");
    }

    reply->deleteLater();
}

// 事件过滤器
bool music::eventFilter(QObject *obj, QEvent *event)
{
    // 播放开关
    if(obj == ui->PlaySongButton)
        handleUserButtonEvent(ui->PlaySongButton, event,
                              "QPushButton { border-radius:20px; background-color:red; }",
                              "QPushButton { border-radius:21px; background-color:rgba(220, 0, 0, 255); }",
                              "QPushButton { border-radius:20px; background-color:rgba(255, 0, 0, 180); }" );
    // 文件按键
    else if(obj == ui->FileSongButton)
    {
        handleButtonEvent(ui->FileSongButton, event);
        // handleTipButtonEvent(ui->FileSongButton, event, "本地");
    }
    // 推荐按键
    else if(obj == ui->WiFiSongButton)
    {
        handleButtonEvent(ui->WiFiSongButton, event);
        // handleTipButtonEvent(ui->WiFiSongButton, event, "推荐");
    }
    // 换肤按键
    else if(obj == ui->ClothButton)
    {
        handleButtonEvent(ui->ClothButton, event);
        // handleTipButtonEvent(ui->ClothButton, event, "换肤");
    }
    // 上一首按键
    else if(obj == ui->LastSongButton)
        handleButtonEvent(ui->LastSongButton, event);
    // 下一首按键
    else if(obj == ui->NextSongButton)
        handleButtonEvent(ui->NextSongButton, event);
    // 模式按键
    else if(obj == ui->ModeSongButton)
        handleButtonEvent(ui->ModeSongButton, event);
    // 声音开关
    else if(obj == ui->VoiceSongButton)
        handleButtonEvent(ui->VoiceSongButton, event);
    // 最小化按键
    else if(obj == ui->ToolMinButton)
        handleButtonEvent(ui->ToolMinButton, event);
    // 最大化按键
    else if(obj == ui->ToolMaxButton)
        handleButtonEvent(ui->ToolMaxButton, event);
    // 关闭按键
    else if(obj == ui->ToolCloseButton)
        handleButtonEvent(ui->ToolCloseButton, event);
    // 搜索按键
    else if(obj == ui->SearchSongButton)
        handleButtonEvent(ui->SearchSongButton, event);

    return QWidget::eventFilter(obj, event);
}

// 本地音乐按钮
void music::on_FileSongButton_clicked()
{
    QDir dir(localmusicPath);
    auto musicList = dir.entryList(QStringList()<<"*.mp3"<<"*.wav"<<"*flac");
    if(!musicList.empty())ui->SongListWidget->clear();
    localmusicList.clear();

    songlistMode = localMode;

    songlistNum = 0;
    for (auto file : musicList)
    {
        songlistNum++;
        localmusicList.append(QUrl::fromLocalFile(QString(localmusicPath) + file)); // 保存音乐完整路径
        QString fileNameWithoutExtension = QFileInfo(file).baseName();              // 获取不带后缀的文件名
        QListWidgetItem *item = new QListWidgetItem(QString("  %1   ").arg(songlistNum, 2, 10, QChar('0')) + fileNameWithoutExtension);
        ui->SongListWidget->addItem(item);
    }

    ui->SongKindsLineEdit->setText("(本地#"+QString::number(songlistNum)+")");
    ui->SongListWidget->setCurrentRow(0);
}

// 播放按钮
void music::on_PlaySongButton_clicked()
{
    if(songlistMode == localMode && localmusicList.empty())
        return;
    else if(songlistMode == navidromeMode && navidrome.ids.empty())
        return;

    // 获取选中的行号
    int index = ui->SongListWidget->currentRow();
    static int last_index = 0;

    switch(mediaPlayer->playbackState())
    {
        // 音乐停止状态，播放选中音乐
        case QMediaPlayer::PlaybackState::StoppedState:
            // 播放对应下标的音乐
            if(songlistMode == localMode)
            {
                mediaPlayer->setSource(localmusicList[index]);
                mediaPlayer->play();
            }
            else if(songlistMode == navidromeMode)
                playNavidromeSong(index);

            handleUserButtonStyle(ui->PlaySongButton, "PlaySongButton.png",
                                  "QPushButton { background-color:red; border-radius:20px; background-color:red; }", this);
            break;
        // 音乐播放状态，暂停音乐
        case QMediaPlayer::PlaybackState::PlayingState:
            if(index == last_index)
            {
                mediaPlayer->pause();
                handleUserButtonStyle(ui->PlaySongButton, "PauseSongButton.png",
                                      "QPushButton { background-color:red; border-radius:20px; background-color:red; }", this);
            }
            else
            {
                if(songlistMode == localMode)
                {
                    mediaPlayer->setSource(localmusicList[index]);
                    mediaPlayer->play();
                }
                else if(songlistMode == navidromeMode)
                    playNavidromeSong(index);
                handleUserButtonStyle(ui->PlaySongButton, "PlaySongButton.png",
                                      "QPushButton { background-color:red; border-radius:20px; background-color:red; }", this);
            }
            break;
        // 音乐暂停状态，继续播放音乐
        case QMediaPlayer::PlaybackState::PausedState:
            if(index != last_index)
            {
                if(songlistMode == localMode)
                {
                    mediaPlayer->setSource(localmusicList[index]);
                    mediaPlayer->play();
                }
                else if(songlistMode == navidromeMode)
                    playNavidromeSong(index);
            }
            else
                mediaPlayer->play();
            handleUserButtonStyle(ui->PlaySongButton, "PlaySongButton.png",
                                  "QPushButton { background-color:red; border-radius:20px; background-color:red; }", this);

            break;
    }

    QFile file(QString(localmusicPath) + "navidrome/navidrome" + QString::number(last_index) + ".mp3");
    file.remove();
    file.close();

    last_index = ui->SongListWidget->currentRow();
}

// 上一首
void music::on_LastSongButton_clicked()
{
    if(songlistMode == localMode && localmusicList.empty())
        return;
    else if(songlistMode == navidromeMode && navidrome.ids.empty())
        return;

    // 获取选中的行号
    int index = ui->SongListWidget->currentRow();

    // 选中上一首
    if(songplayMode == singleSongMode)
    {
        mediaPlayer->stop();
        mediaPlayer->setPosition(0);
    }
    else
    {
        if(index <= 0)
        {
            if(songlistMode == localMode)
                index = localmusicList.size() - 1;
            else if(songlistMode == navidromeMode)
                index = navidrome.ids.size() - 1;
        }
        else index --;
    }
    ui->SongListWidget->setCurrentRow(index);
}

// 下一首
void music::on_NextSongButton_clicked()
{
    if(localmusicList.empty())
        return;

    // 获取选中的行号
    int index = ui->SongListWidget->currentRow();
    static int last_index;

    // 选中下一首
    if(songplayMode == singleSongMode)
    {
        mediaPlayer->stop();
        mediaPlayer->setPosition(0);
        songtimesNum = 0;
        ui->SongWordsListWidget->setCurrentRow(songtimesNum);
    }
    else if(songplayMode == loopSongMode)
    {
        if(songlistMode == localMode)
        {
            if(index >= localmusicList.size() - 1)
                index = 0;
            else index ++;
        }
        else if(songlistMode == navidromeMode)
        {
            if(index >= navidrome.ids.size() - 1)
                index = 0;
            else index ++;
        }

    }
    else if(songplayMode == randomSongMode)
    {
        last_index = index;
        do {
            if(songlistMode == localMode)
                index = QRandomGenerator::global()->bounded(localmusicList.size());
            else if(songlistMode == navidromeMode)
                index = QRandomGenerator::global()->bounded(navidrome.ids.size());
        } while (index == last_index);
    }
    ui->SongListWidget->setCurrentRow(index);
}

// 播放模式
void music::on_ModeSongButton_clicked()
{
    songplayMode++;
    if(songplayMode > 2)songplayMode = 0;
    QIcon Icon;
    QString Pic;
    if(songplayMode == singleSongMode)Pic = "SingleSongMode.png"; // 单曲循环
    if(songplayMode == loopSongMode)Pic = "LoopSongMode.png";     // 列表循环
    if(songplayMode == randomSongMode)Pic = "RandomSongMode.png"; // 随机播放
    Icon.addFile(assetsPath + Pic);
    ui->ModeSongButton->setIcon(Icon);
}

// 声音
void music::on_VoiceSongButton_clicked()
{
    static float voiceNum = 0.5;

    voiceNum+=0.25;
    if(voiceNum > 1)voiceNum = 0;
    audioOutput->setVolume(voiceNum);

    QIcon Icon;
    QString Pic;

    if(voiceNum == 0)
        Pic = "VoiceCloseButton.png";
    else
        Pic = "VoiceOpenButton.png";

    Icon.addFile(assetsPath + Pic);
    ui->VoiceSongButton->setIcon(Icon);

    if(voiceNum == 0)ui->VoiceSongLabel->setText("");
    else if(voiceNum == 0.25)ui->VoiceSongLabel->setText("·");
    else if(voiceNum == 0.50)ui->VoiceSongLabel->setText("··");
    else if(voiceNum == 0.75)ui->VoiceSongLabel->setText("···");
    else if(voiceNum == 1)ui->VoiceSongLabel->setText("····");
}

// 换肤
void music::on_ClothButton_clicked()
{
    static int clouthState = 0;
    QString clouthName;

    clouthState++;
    if(clouthState > 4)clouthState = 0;
    if(clouthState == blackClouthMode)clouthName = QString(blackClouth);
    if(clouthState == pinkClouthMode)clouthName = QString(pinkClouth);
    if(clouthState == redClouthMode)clouthName = QString(redClouth);
    if(clouthState == blueClouthMode)clouthName = QString(blueClouth);
    if(clouthState == greenClouthMode)clouthName = QString(greenClouth);

    ui->BackGroundBox->setStyleSheet("QGroupBox{border:transparent;border-radius:15px;" + clouthName);
    ui->PlaySongBox->setStyleSheet("QGroupBox{border:transparent;border-bottom-left-radius:15px; border-bottom-right-radius:15px;" + clouthName);
}

// 推荐歌曲
void music::on_WiFiSongButton_clicked()
{
    songlistMode = navidromeMode;

    songlistNum = 0;
    ui->SongListWidget->clear();

    getNavidromeSongList();

    if(!navidrome.titles.empty())
    {
        for (auto file : navidrome.titles)
        {
            songlistNum++;
            QListWidgetItem *item = new QListWidgetItem(QString("  %1   ").arg(songlistNum, 2, 10, QChar('0')) + file + "-" + navidrome.artists[songlistNum-1]);
            ui->SongListWidget->addItem(item);
        }
    }
    else
        ui->SongListWidget->addItem("加载失败，请检查网络");

    ui->SongKindsLineEdit->setText("(推荐#"+QString::number(songlistNum)+")");
    ui->SongListWidget->setCurrentRow(0);

    QDir dir(QString(localmusicPath) + "navidrome");
    auto list = dir.entryList(QStringList()<<"*.mp3");
    if(!list.empty())
    {
        for(auto filePath : list)
        {
            QFile file(QString(localmusicPath) + "navidrome//" + filePath);
            file.remove();
            file.close();
        }
    }
}

// 搜索
void music::on_SearchSongButton_clicked()
{
    songlistMode = navidromeMode;

    songlistNum = 0;
    ui->SongListWidget->clear();

    searchNavidromeSongList(ui->SongSearchLineEdit->text());

    if(!navidrome.titles.empty())
    {
        for (auto file : navidrome.titles)
        {
            songlistNum++;
            QListWidgetItem *item = new QListWidgetItem(QString("  %1   ").arg(songlistNum, 2, 10, QChar('0')) + file + "-" + navidrome.artists[songlistNum-1]);
            ui->SongListWidget->addItem(item);
        }
    }
    else
        ui->SongListWidget->addItem("加载失败，请检查网络");

    ui->SongKindsLineEdit->setText("(搜索#"+QString::number(songlistNum)+")");
    ui->SongListWidget->setCurrentRow(0);

    QDir dir(QString(localmusicPath) + "navidrome");
    auto list = dir.entryList(QStringList()<<"*.mp3");
    if(!list.empty())
    {
        for(auto filePath : list)
        {
            QFile file(QString(localmusicPath) + "navidrome//" + filePath);
            file.remove();
            file.close();
        }
    }
}

